package com.xuan.yrmanage.dao;



import com.xuan.yrmanage.domain.Menu;
import com.xuan.yrmanage.domain.Permission;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;

/**
 * FileName: MenuMapper
 * Author:   xuan zongjun
 * Date:     2020/2/26 10:17
 * Description:
 */

@Mapper
public interface MenuMapper {

    //获取列表
    @SelectProvider(type = MenuMapper.MenuProvider.class, method = "findAll")
    @Results(id = "menuMap", value = {
            @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "link_url", property = "linkUrl"),
            @Result(column = "path", property = "path"),
            @Result(column = "priority", property = "priority"),
            @Result(column = "icon", property = "icon"),
            @Result(column = "description", property = "description"),
            @Result(column = "parent_menu_id", property = "parentMenuId"),
            @Result(column = "level", property = "level"),
            @Result(column = "icon", property = "icon"),
            @Result(column = "create_time", property = "createTime"),
    })
    List<Menu> findAll(@Param("pageIndex") int pageIndex, @Param("pageSize") int pageSize, @Param("name") String name);

    //获取总数
    @SelectProvider(type = MenuMapper.MenuProvider.class, method = "getCount")
    int getCount(String name);

    //根据ID查询
    @Select("select * from t_menu where  is_delete=0 and id=#{menuId}")
    @ResultMap("menuMap")
    Menu findById(@Param("menuId") Integer menuId);

    //插入
    @Insert("insert into t_menu " +
            " (id,name,link_url,priority,icon,description,parent_menu_id,level,is_delete,create_time,create_by) " +
            " values " +
            " (#{id},#{name},#{linkUrl},#{priority},#{icon},#{description},#{parentMenuId},#{level},#{isDelete},#{createTime},#{createBy})")
    @SelectKey(keyColumn = "id", keyProperty = "id", resultType = int.class, before = false, statement = "select last_insert_id()")
    void insert(Menu menu);

    //修改菜单
//    @Update(" update t_menu set  name=#{name},link_url=#{linkUrl},priority=#{priority},icon=#{icon},description=#{description}," +
//            " parent_menu_id=#{parentMenuId},update_time=#{updateTime},update_by=#{updateBy} " +
//            " where id =#{id}")
    @UpdateProvider( type = MenuMapper.MenuProvider.class, method = "update")
    int update(Menu menu);

    //删除菜单
    @Delete("delete  from t_menu where id=#{menuId}")
    void delete(Integer menuId);

    //插入菜单和角色的关系
    @Insert( "insert t_menu_permission (menu_id,permission_id) values (#{menuId},#{permissionId})" )
    void insertMenuPermission(@Param("menuId") Integer menuId, @Param("permissionId") Integer permissionId);

    //删除菜单和角色的对应关系
    @Delete( "delete from t_menu_permission where menu_id = #{menuId}" )
    void  deleteMenuPermission(@Param("menuId") Integer menuId);

    //根据菜单名称查询菜单
    @Select("select count(*) from t_menu where name=#{name}")
    int findByName(String name);

   //根据菜单和角色，获取选中的权限
    @Select(" select DISTINCT p.*,p.function_key functionKey,tmp.*  from t_permission p " +
            " join t_role_permission trp on p.id = trp.permission_id" +
            " join t_menu_permission tmp on tmp.permission_id = trp.permission_id" +
            " where tmp.menu_id = #{menuId} and role_id =#{roleId}" )
    List<Permission> findPermissionByMenuIdRoleId(@Param("menuId") Integer menuId, @Param("roleId") Integer roleId);


    //根据菜单下全部的权限
    @Select(" select *,function_key functionKey from t_permission " +
            " where id in (select permission_id from t_menu_permission where menu_id=#{menuId})" )
    List<Permission> findPermissionByMenuId(@Param("menuId") Integer menuId);

    //返回1级菜单
    @Select("select * from t_menu where is_delete=0 and  level=1 order by priority asc")
    @ResultMap("menuMap")
    List<Menu> getOneLevelMenu();


    class MenuProvider {

        public String findAll(@Param( "pageIndex" ) int pageIndex, @Param( "pageSize" ) int pageSize, @Param( "name" )String name) {
            SQL sql = new SQL() {
                {
                    SELECT( "*" );
                    FROM( "t_menu" );
                    WHERE( "is_delete=0" );
                    if (StringUtils.isNotEmpty( name )) {
                        WHERE( "(id = #{name} or name like \"%\" #{name}\"%\")" );
                    }
                    ORDER_BY( "create_time desc " );
                }
            };
            String sqlStr = sql.toString();
            if (pageIndex != 0 && pageSize != 0) {
                int start = (pageIndex - 1) * pageSize;
                sqlStr += " limit " + start + "," + pageSize;
            }

            return sqlStr;
        }

        public String getCount(String name) {
            SQL sql = new SQL() {
                {
                    SELECT( "count(*)" );
                    FROM( "t_menu" );
                    WHERE( "is_delete=0" );
                    if (StringUtils.isNotEmpty( name )) {
                        WHERE( "(id = #{name} or name like \"%\" #{name}\"%\")" );
                    }
                }
            };
            String sqlStr = sql.toString();
            return sqlStr;
        }

        public String update(Menu menu){
            SQL sql = new SQL() {
                {
                    UPDATE( "t_menu" );
                    if(menu.getName()!=null){
                        SET( "name=#{name}" );
                    }
                    if(menu.getLinkUrl()!=null){
                        SET( "link_url=#{linkUrl}" );
                    }
                    if(menu.getPriority()!=null){
                        SET( "priority=#{priority}" );
                    }
                    if(menu.getIcon()!=null){
                        SET( "icon=#{icon}" );
                    }
                    if(menu.getDescription()!=null){
                        SET( "description=#{description}" );
                    }
                    if(menu.getParentMenuId()!=null){
                        SET( "parent_menu_id=#{parentMenuId}" );
                    }
                    SET("update_time = #{updateTime}"  );
                    SET("update_by = #{updateBy}"  );

                    WHERE( "id =#{id}" );

                }
            };
            String sqlStr = sql.toString();
            return sqlStr;
        }


    }


}
